package com.crazy.multids.config.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * 多数据源代理类
 *
 * @author crazyhu@wezhuiyi.com
 * @date 2018-09-16 15:19
 **/
@Slf4j
public class RoutingDataSourceProxy extends AbstractRoutingDataSource {

    private AtomicInteger count = new AtomicInteger(0);

    @Override
    protected Object determineCurrentLookupKey() {
        DataSourceEnum dataSourceType = DataSourceContextHolder.getDataSourceType();
        if (dataSourceType.equals(DataSourceEnum.WRITE)) {
            return DataSourceNames.DS_MASTER;
        }

        // 如果是从库，则选择其中之一
        int number = count.getAndAdd(1);
        int lookupKey = number % 2;
        log.info("使用数据库crazy.datasource.slave_" + lookupKey);
        return "crazy.datasource.slave_" + lookupKey;
    }

}
